/*
 * @Author: txy 
 * @Date: 2019-04-01 14:33:33 
 * @Last Modified by: txy
 * @Last Modified time: 2020-07-31 16:38:54
 */

layui.use(['tree', 'treeGrid', 'zlpoptree', 'zlTheme', 'zlPinYin', 'zlContext','upload'], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , zlPinYin = layui.zlPinYin
        , zlTheme = layui.zlTheme
        , layer = layui.layer
        , upload = layui.upload
        , treeGrid = layui.treeGrid
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , OK = zlConfig.global.result.okState
        , form = layui.form
        , tableId = 'treeFormTable'
        , ptable
        , fromlayerIndex
        , isloadsearch = false
        , fullheight
        , _EXT = 'pm'
        , _MIME = 'PageModel/pm';
    fullheight = zlContext.setMaxHeihgt(0);

    // 渲染表格
    var loadingLayer = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });
    ptable = treeGrid.render({
        id: tableId
        , elem: '#' + tableId
        , method: 'post'
        , cellMinWidth: 100
        , height: fullheight
        , url: layui.cache['contentPath'] + '/manager/coremodeldesign/query'
        , idField: 'RWID'
        , treeId: 'RWID'//树形id字段名称
        , treeUpId: 'SYS_PARENTID'//树形父id字段名称
        , treeShowName: 'OBJNAME'//以树形式显示的字段
        , isOpenDefault: false
        , chkboxType: { "Y": "", "N": "" }//父子节点的关联关系 默认值：{ "Y": "ps", "N": "ps" }
        , loading: false
        , cols: [[
            { type: 'numbers', fixed: '' }
            , { type: 'checkbox', fixed: '' }
            , { field: 'OBJNAME', width: 300, title: '名称', sort: true }
            , { field: 'OBJCODE', width: 300, title: '编号', sort: true }
            , { fixed: 'right', field: 'OPTION', width: 330, title: '操作', align: 'center', toolbar: '#form-operation-btn'}
        ]]
        , page: false
        , limit: 9999
        , response: zlConfig.global.gridResponse
        , done: function (res, curr, count) {
            layer.close(loadingLayer)
            formTreeAction.import();
        }
    });

    var formTreeAction = {
        treeFormEdit: function (rows, type, readonly) {
            // 弹出框内容
            var readonly = readonly && readonly != 0 ? 'disabled' : '';
            var frm = [
                '<div class="site-block"> <form id ="frmGridForm" class="layui-form"  action="">'
                , '	<div class="layui-form-item layui-hide">'
                , '		<div class="layui-input-block">'
                , '			<input type="text" name="EDITTYPE" class="layui-input">'
                , '			<input type="text" name="RWID" class="layui-input">'
                , '			<input type="text" name="SYS_PARENTID" class="layui-input">'
                , '			<input type="text" name="SYS_PARENTS" class="layui-input">'               
                , '		</div>'
                , '	</div>'
                , '	<div class="layui-form-item">'
                , '		<label class="layui-form-label">表单名称</label>'
                , '		<div class="layui-input-block">'
                , '			<input type="text" name="OBJNAME" required ' + readonly + ' lay-verify="required" placeholder="请输入名称" class="layui-input" maxlength="85">'
                , '		</div>'
                , '	</div>'
                , '	<div class="layui-form-item">'
                , '		<label class="layui-form-label">编号</label>'
                , '		<div class="layui-input-block">'
                , '			<input type="text" name="OBJCODE" required ' + readonly + ' lay-verify="required" placeholder="请输入编号" class="layui-input" maxlength="60">'
                , '		</div>'
                , '	</div>'
                , '   <div class="layui-form-item">'
                , '        <div class="layui-col-md12">'
                , '             <label name="pfunction" class="layui-form-label">上级表单</label>'
                , '             <div class="layui-input-block">'
                , '                  <div name="SYS_PARENTID" zlcomponent class="layui-form-select zlpoptree" text="" value="">'
                , '                   </div>'
                , '             </div>'
                , '         </div>'
                , '   </div>'
                // , '	<div class="layui-form-item">'
                // , '		<label class="layui-form-label">表单模板</label>'
                // , '		<div class="layui-input-block">'
                // , '	  		<select name="MODELD_DFID" ' + readonly + ' placeholder="请选择类型"  zlcomponent class="select-ext" settings="{titlefield: \'VALUE\', valuefield: \'CODE\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=439BD47789C94934ACAF625B1F697DFC\'}">'
                // , '	  		</select>'
                // , '		</div>'
                // , '	</div>'
                // , '	<div class="layui-form-item">'
                // , '		<label class="layui-form-label">表模型</label>'
                // , '		<div class="layui-input-block">'
                // , '	  		<div name="MODELD_TABLEID" zlcomponent lay-verify="required" ' + readonly + ' class="layui-form-select zlpoptree" text="" value="" settings=""></div>'
                // , '	  		</select>'
                // , '		</div>'
                // , '	</div>'
                , '	<div class="layui-form-item' + (readonly == 'disabled' ? ' layui-hide"' : '"') + '>'
                , '		<div class="layui-input-block">'
                , '		  <button class="layui-btn" lay-submit lay-filter="frmGridForm"  ' + readonly + '>保存</button>'
                , '		</div>'
                , '	</div>'
                , '</form></div>'
            ];
            var settings = "{chkboxType:'{\"Y\":\"\", \"N\": \"\" }',checkbox:true,multselect:true,dataurl:'" + layui.cache['contentPath'] + "/manager/coretables/queryext',method:'post',id:'RWID',idKey:'RWID',name:'MX_MINGC',formtitle:'请选择表模型'}"
            var psettings = "{dataurl:layui.cache['contentPath'] + '/manager/coremodeldesign/query',method:'post',formtitle:'选择上级表单',edittype:'edit'}";
            fromlayerIndex = layer.open({
                type: 1,
                id: 'addFormLayer',
                area: ['100%', '100%'],
                content: frm.join(''),
                title: readonly == 'disabled' ? '查看表单' : (type == 'edit' ? '编辑表单' : '新增表单'),
                success: function () {
                    $('#frmGridForm div[name="MODELD_TABLEID"]').attr("settings",settings);
                    $('#frmGridForm div[name="SYS_PARENTID"]').attr("settings", psettings);
                    if (rows.length > 0 && type == 'new') {
                        $('#frmGridForm div[name="SYS_PARENTID"]').attr("value", rows[0].RWID);
                        $('#frmGridForm div[name="SYS_PARENTID"]').attr("text", rows[0].OBJNAME);
                    }
                    if (type == 'edit' || type == 'copy') {
                        $('#frmGridForm input[name="RWID"]').val(rows[0].RWID);
                        $('#frmGridForm div[name="MODELD_TABLEID"]').attr("value",rows[0].MODELD_TABLEID);
                        $('#frmGridForm div[name="MODELD_TABLEID"]').attr("text",rows[0].MODELD_TABLENAME);
                        zlContext.autoFill($('#frmGridForm'), rows[0]);
                        $('#frmGridForm input[name=EDITTYPE]').val(type);
                    } else {
                        /**设置隐藏属性*/
                        $('#frmGridForm input[name=EDITTYPE]').val('new');
                        form.render();
                        $('#frmGridForm input[name=OBJNAME]').change(function () {
                            var v = $('#frmGridForm input[name=OBJNAME]').val();
                            /**根据用户名生成编号 */
                            var v1 = zlPinYin.C(v);
                            $('#frmGridForm input[name=OBJCODE]').val(v1);
                            form.render();
                        });
                    }

                }
            });
        }
        // 查看表单
        , viewRow: function (row) {
            formTreeAction.treeFormEdit(row, 'edit', true);
        }
        // 新建表单
        , newRow: function (row) {
            formTreeAction.treeFormEdit(row, 'new');
        }
        // 修改表单
        , editRow: function (row) {
            formTreeAction.treeFormEdit(row, 'edit');
        }
        // 复制表单
        , copyRow: function (row) {
            formTreeAction.treeFormEdit(row, 'copy');
        }
        // 删除表单
        , deleteRows: function (row){
            var canpost = true;
            for (var i = 0; i < row.length; i++) {
                if (row[i].children.length > 0) {
                    zlContext.warnMsg(row[i].OBJNAME + "该节点下还有子表单，请先删除子表单！");
                    canpost = false;
                    return;
                }
            }
            if (!canpost) {
                return;
            }
            zlContext.confirm('询问', '是否要删除选择的表单吗？', function (index) {
                //删除对应行（tr）的DOM结构
                //向服务端发送删除指令
                var ids = [];
                row.forEach(function (v) { ids.push(v.data ? v.data['RWID'] : v['RWID']); });
                zlContext.deletePost(layui.cache['contentPath'] + '/manager/coremodeldesign/remove', ids, function (result) {
                    if (result[statusName] == OK) {
                        treeGrid.reload('treeFormTable', {
                            url: layui.cache['contentPath'] + '/manager/coremodeldesign/query'
                        });
                        form.render();
                        zlContext.successMsg('删除成功');
                    }
                    else {
                        zlContext.errorMsg(result[msgName]);
                    }
                    layer.close(index);
                });
            });
        }
        , sumbit: function (fields) {
            var editType = $('#frmGridForm input[name=EDITTYPE]').val();            
            fields.MODELD_TABLENAME=$('input[name="inputMODELD_TABLEID"]').val();
            if (editType == 'new') {
                zlContext.put(layui.cache['contentPath'] + '/manager/coremodeldesign/add', fields, function (result) {
                    if (result[statusName] == OK) {
                        treeGrid.reload('treeFormTable', {
                            url: layui.cache['contentPath'] + '/manager/coremodeldesign/query'
                        });
                        layer.close(fromlayerIndex);
                        zlContext.successMsg('保存成功');
                        return true;
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            }
            if (editType == 'edit') {
                zlContext.post(layui.cache['contentPath'] + '/manager/coremodeldesign/modify', fields, function (result) {
                    if (result[statusName] == OK) {
                        treeGrid.reload('treeFormTable', {
                            url: layui.cache['contentPath'] + '/manager/coremodeldesign/query'
                        });
                        layer.close(fromlayerIndex);
                        zlContext.successMsg('保存成功');
                        return true;
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            }
            if (editType == 'copy') {
                zlContext.post(layui.cache['contentPath'] + '/manager/coremodeldesign/copy', fields, function (result) {
                    if (result[statusName] == OK) {
                        treeGrid.reload('treeFormTable', {
                            url: layui.cache['contentPath'] + '/manager/coremodeldesign/query'
                        });
                        layer.close(fromlayerIndex);
                        zlContext.successMsg('复制成功');
                        return true;
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            }
            return false;
        }
        // 设计
        , design: function (row) {
			var frmobj = layer.open({
				type: 2,
				limit: 999,
				maxmin: true,
				title: '表单设计-[<strong>'+row.OBJNAME+'</strong>]',  
				id: 'formDesignLayer',
				area: ['100%', '100%'],
                method:"post",
                content: layui.cache['contentPath'] + '/manager/coremodeldesign/design',
                zIndex: layer.zIndex, //重点1
                params:{modelId:row.RWID},
                success:function(layero){
                    layer.setTop(layero); //重点2
                    var currentThemeData = sessionStorage.getItem('zltheme') ? JSON.parse(sessionStorage.getItem('zltheme')) : zlTheme.defaulTheme;
                    zlTheme.setTheme(currentThemeData);
                },
				cancel: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    body.find('#btnPageEditState').trigger('click');
                    if(body.find('#btnPageEditState').attr('state') == 'true'){
                        var top = zlContext.kdayunIframe();
                        top['layer'].confirm('表单设计有改动，是否要保存再关闭！',{
                            btn: ['保存并关闭', '放弃保存', '取消'],
                            anim: 1,
                            icon: 3,
                            title:"提示"},
                            function(confirmIndex){
                                top.layer.close(confirmIndex);
                                body.find('#savejson').trigger('click');
                                layer.close(index)
                                return false;
                            },
                            function(confirmIndex){
                                top.layer.close(confirmIndex);
                                layer.close(index)
                                return false;
                            },
                            function(confirmIndex){
                                top.layer.close(confirmIndex);
                            }
                        )
                        return false;
                    }else{
                        layer.close(index)
                        return false;
                    }
				}
			});
        }
        // 预览
        , preview: function (row){
            openPostWindow("预览",row.RWID,'fullscreen=yes');
        },
        export:function(row){
            if ($("#ifexport").length == 0) {
				$("body").append('<iframe id="ifexport" style="display:none"></iframe>');
            }
            loadingLayer = layer.msg('下载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
            var _downloadid = new Date().getTime();
			$("#ifexport").attr("src", layui.cache['contentPath'] + '/manager/coremodeldesign/download?id=' + row['RWID'] + '&_downloadid=' + _downloadid);
			var iframe = document.getElementById('ifexport');
			iframe.onload = iframe.onreadystatechange = function iframeload() {
                if(intervalId){
                    clearInterval(intervalId);
                }
                layer.close(loadingLayer);
                if (!iframe.readyState || iframe.readyState == "complete") {
                	var iframeText = document.getElementById('ifexport').contentWindow.document;
					iframeText = $(iframeText).text();
					if(iframeText){
						var obj = JSON.parse(iframeText);
						zlContext.errorMsg(obj.msg);
					}
                	
                }
            };
            intervalId = setInterval(function(){
                var cookieName = '_downloadid' + _downloadid;
                var cookieValue = zlContext.getCookieValue(cookieName);
                if(cookieValue && cookieValue == _downloadid){
                    layer.close(loadingLayer);
                    if(intervalId){
                        clearInterval(intervalId);
                        intervalId = undefined;
                    }
                }
            }, 500);
        },
        import:function(){
            var currentId='';
            upload.render({
                elem: '.modelImport'
                , url: layui.cache['contentPath'] + '/manager/coremodeldesign/upload/'
                , data: {
                    id: function () {
                        return currentId;
                    }
                }
                //, accept: 'file'
                , acceptMime: _MIME
                , exts: _EXT
                , choose: function(obj){
                    currentId = $(this.item).attr('data-id')
                }
                , before: function () {
                    winIndex = layer.msg('导入中，请稍候...', { icon: 16, time: false, shade: 0.1 });
                }
                , done: function (res, index, upload) {
                    layer.close(winIndex);
                    if (res[statusName] != OK) {
                        return layer.msg('导入失败' + res[msgName]);
                    }
                    else {
                        treeGrid.reload('tbReport');
                    }
                    zlContext.successMsg('导入完毕');
                }
            })
        }
        
    }


    //展开或折叠全部
    $('#btnopenall').on('click', function () {
        var treedata = treeGrid.getDataTreeList('treeFormTable');
        if ($(this).find('i').hasClass("layui-icon-down")) {
            $(this).find('i').removeClass("layui-icon-down").addClass("layui-icon-up");
            $(this).find('span').text("收起全部")
        } else {
            $(this).find('i').removeClass("layui-icon-up").addClass("layui-icon-down");
            $(this).find('span').text("展开全部")
        }
        treeGrid.treeOpenAll('treeFormTable', !treedata[0][treeGrid.config.cols.isOpen]);
    });
    // 新增
    $('#btnnew').on('click', function () {
        var checkStatus = treeGrid.checkStatus('treeFormTable')
            , rows = checkStatus.data;
        if (rows.length > 1) {
            zlContext.warnMsg("不能同时两个节点下增加表单！");
            return;
        }
        formTreeAction.newRow(rows);
    });
    // 修改
    $('#btnedit').on('click', function () {
        var checkStatus = treeGrid.checkStatus('treeFormTable')
            , rows = checkStatus.data;
        if (rows.length == 0) {
            zlContext.warnMsg("请选择表单数据！");
            return;
        }
        if (rows.length > 1) {
            zlContext.warnMsg("不能同时两个表单！");
            return;
        }
        formTreeAction.editRow(rows);
    });
    // 删除
    $('#btndel').on('click', function () {
        var checkStatus = treeGrid.checkStatus('treeFormTable')
            , rows = checkStatus.data;
        if (rows.length == 0) {
            zlContext.warnMsg("请选择需要删除的表单！");
            return;
        }
        formTreeAction.deleteRows(rows);
    });

    // 提交
    form.on('submit(frmGridForm)', function (frm) {
        if ($(frm.elem).hasClass('getField')) {
            formTreeAction.newFields = frm.field;
            return false;
        }
        return formTreeAction.sumbit(frm.field);
    });

    // 操作栏事件
    //监听行工具事件
	treeGrid.on('tool(treeFormTable)', function (obj) {
		var row = obj.data;
		var layEvent = obj.event;
		if (layEvent === 'del') { //删除
            formTreeAction.deleteRows([row]);
		} else if (layEvent === 'edit') { //编辑
            formTreeAction.editRow([row]);
		} else if (layEvent == 'design') {
			formTreeAction.design(row);
		} else if (layEvent == 'export') {
			formTreeAction.export(row);
		} else if(layEvent == 'preview'){
            formTreeAction.preview(row);
        }else if(layEvent == 'copy'){ //复制
            formTreeAction.copyRow([row]);
        }
        
	});
    //当浏览器窗口大小改变时，设置显示内容的高度  
    window.onresize = function () {
        fullheight = zlContext.setMaxHeihgt(0);
    }

    $('#btnSeacher').on('click', function () {
        isloadsearch = true;
        var seachervalue = $('#edtSeacherValue').val();
        treeGrid.reload('treeFormTable', {
            url: layui.cache['contentPath'] + '/manager/coremodeldesign/query',
            method:'POST',
            where :{seachervalue:seachervalue}
        });
    });

    $('#edtSeacherValue').on('keyup', function (event) {
		var keyCode = event.keyCode;
		if (keyCode == 13) {
			$('#btnSeacher').trigger('click');
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
			$('#btnSeacher').trigger('click');
			isloadsearch = false;
		}
    });
    

//以post形式打开新的页面，可以传递多个参数
function openPostWindow(windowname,model,password){         
    var tempForm = document.createElement("form");       
    tempForm.id="tempForm1";         
    tempForm.method="get";        
    tempForm.action=layui.cache['contentPath'] + '/manager/coremodeldesign/show?tokenId='+getTokenId();   
    //open方法不能设置请求方式，一般网页的post都是通过form来实现的。  
    //如果仅仅模拟form的提交方式，那么open方法里那种可设置窗体属性的参数又不能用。  
    //最后想办法整了这么一个两者结合的方式，将form的target设置成和open的name参数一样的值，通过浏览器自动识别实现了将内容post到新窗口中  
    tempForm.target=windowname;         
    tempForm.innerHTML="<input type='hidden' name='model' value='1'/><input type='hidden' name='modelId' value='"+model+"'/>";
    // tempForm.attachEvent("onsubmit",function(){ openWindow(name); });     //IE
    tempForm.addEventListener("onsubmit",function(){ window.open('about:blank',windowname); });   //chrome    
    document.body.appendChild(tempForm);          
    //tempForm.fireEvent("onsubmit"); //IE    
    tempForm.dispatchEvent(new Event("onsubmit"));//chrome    
    //必须手动的触发，否则只能看到页面刷新而没有打开新窗口  
    tempForm.submit();       
    document.body.removeChild(tempForm);      
 }   




});  